import serverUrl from '../config/url'
import Vue from 'vue'
import Axios from 'axios'

let utils = {}

utils.fileSaveAs = (url, params) => {
  let paramsStr = ''
  for (let key in params) {
    if (typeof params[key] === 'object') {
      // 对象类型，需要判断是否有id，并拼接成对应的参数格式
      if (params[key].id) {
        paramsStr = paramsStr + `&${key}.id=${params[key].id}`
      }
    } else {
      paramsStr = paramsStr + `&${key}=${params[key]}`
    }
  }

  if (paramsStr.length > 0) {
    paramsStr = `?${paramsStr.substring(1)}`
  }

  let a = document.createElement('a')
  a.href = `${serverUrl}${url}${paramsStr}`
  a.target = '_blank'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

/** 导出需token认证 */
utils.fileExportAs = (url, params, fileName) => {
  let paramsStr = ''
  for (let key in params) {
    if (typeof params[key] === 'object') {
      // 对象类型，需要判断是否有id，并拼接成对应的参数格式
      if (params[key].id) {
        paramsStr = paramsStr + `&${key}.id=${params[key].id}`
      } else if (key === 'sys_search') {
        // 对于查询条件进行改造
        let cacheSysSearch = params[key]
        let sysSearch = []
        for (const key in cacheSysSearch) {
          if (cacheSysSearch.hasOwnProperty(key)) {
            if ((typeof (cacheSysSearch[key]) === 'string' && cacheSysSearch[key].length === 0) || !cacheSysSearch[key]) {} else {
              sysSearch.push({
                name: key,
                value: cacheSysSearch[key],
                pattern: 'like'
              })
            }
          }
        }
        paramsStr = paramsStr + `&${key}=${JSON.stringify(sysSearch)}`
      }
    } else {
      paramsStr = paramsStr + `&${key}=${params[key]}`
    }
  }
  if (paramsStr.length > 0) {
    paramsStr = `?${paramsStr.substring(1)}`
  }
  Axios
    .get(`${url}${paramsStr}`, {
      responseType: 'blob'
    })
    .then(resp => {
      let blob = new Blob([resp], {
        type: 'application/octet-stream'
      })
      let a = document.createElement('a')
      a.href = URL.createObjectURL(blob)
      a.target = '_blank'
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    })
}

utils.treeToArray = (treeData, parent, level, expandedAll) => {
  let tempArr = []

  treeData.forEach((element) => {
    if (typeof (element._expanded) === 'undefined') {
      Vue.set(element, '_expanded', expandedAll)
    }

    if (parent) {
      Vue.set(element, '_parent', parent)
    }

    let _level = 0
    if (level !== null && level !== undefined) {
      _level = level + 1
    }

    Vue.set(element, '_level', _level)

    tempArr.push(element)

    if (element.children && element.children.length > 0) {
      let children = utils.treeToArray(element.children, element, _level, expandedAll)
      tempArr = tempArr.concat(children)
    }
  })

  return tempArr
}

utils.arrayToTree = (array) => {
  let result = array.filter(item => !item.parentmenuid)

  let recursion = (parents) => {
    parents.forEach(parent => {
      parent.children = array.filter(item => {
        return item.parentmenuid === parent.menuid
      })
      if (parent.children.length) {
        recursion(parent.children)
      }
    })
  }

  recursion(result)

  return result
}

utils.transformOrgTree = (array) => {
  let result
  let findRootNode = (parentId) => {
    return array.find(item => parentId === item.orgid)
  }

  /** 遍历获取根节点，对于当前系统机构，只会有一个根节点，不能单纯通过 parentorgid 是否为空进行判断根节点 */
  for (let index = 0; index < array.length; index++) {
    if (!findRootNode(array[index].parentorgid)) {
      result = array[index]
      break
    }
  }

  let recursion = (parentNode) => {
    parentNode.forEach(parent => {
      parent.children = array.filter(item => {
        return item.parentorgid ? item.parentorgid.toLowerCase() === parent.orgid.toLowerCase() : null
      })
      if (parent.children.length) {
        recursion(parent.children)
      }
    })
  }

  recursion([result])

  return [result]
}

export default utils
